<!--
/**
 * @author xuyh0817
 * @email xuyh0817@foxmail.com
 * @date 2022-10-19 20:18
 * @version 1.0.0
 * @doc todo
 * @website todo
 * @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
 * @description todo
 */
 -->
<template>
  <div class="x-render-ops">
    <div class="x-render-ops-btn">
      <el-button size="mini" type="primary" :disabled="!!data.title" @click="handleAdd('title')">添加标题</el-button>
      <el-button size="mini" type="primary" @click="handleAdd('img')">添加图片</el-button>
      <el-button size="mini" type="primary" @click="handleAdd('text')">添加正文</el-button>
      <el-button size="mini" type="success" @click="doExport" icon="el-icon-download">下载</el-button>
    </div>


    <ul class="x-render-drag-container">
      <li class="x-render-li-item unmover" :class="{'x-render-drag-active':active === -1}" v-if="data.title"
          @click="$emit('update:active',-1)">
        <span>1. 标题</span>
        <i class="el-icon-close" @click.prevent="handleRemove(-1)"></i>
      </li>

      <template v-for="(item, index) in data.content">
        <li class="x-render-li-item" :class="{'x-render-drag-active': active === index }" :key="item.id"
            @click="$emit('update:active',index)">
            <span>
              {{ data.title ? index + 2 : index + 1 }}.
              {{ item.type === 'img' ? '图片' : item.text.trim().substring(0, 10) }}
            </span>
          <div class="x-render-li-item-icon">
            <i class="el-icon-top" @click="handleUp(index)" v-if="index !== 0"></i>
            <span v-else></span>
            <i class="el-icon-bottom" @click="handleDown(index)" v-if="index !== data.content.length - 1"></i>
            <span v-else></span>
            <i class="el-icon-close" @click="handleRemove(index)"></i>
          </div>
        </li>
      </template>
    </ul>
    <input v-if="fileShow" style="display: none;" name="opsFileChange" type="file" accept="image/jpeg,image/png"
           ref="opsFileChange"
           @change="handleFileChange"></input>
  </div>

</template>

<script>
import html2canvas from 'html2canvas'


function parseTime(date = new Date(), format = 'yyyy-MM-dd') {
  if (arguments.length === 0 || !date) {
    return ''
  }

  if (typeof (date) !== 'object') {
    date = new Date(date)
  }

  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return format
}

export default {
  name: "MoOps",
  props: {
    data: {
      type: Object,
      default: () => {
        return {
          title: undefined,
          content: []
        }
      }
    },
    active: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      fileShow: false
    }
  },
  computed: {
    draggableOptions: {
      get() {
        return {
          filter: '.unmover',
          group: 'XRenderMemo',
          animation: 300,
          draggable: '.x-render-li-item',
          handler: '.x-render-li-item'
        }
      }
    },
  },
  methods: {
    handleRemove(index) {
      const {data} = this
      const tmp = {...data}
      if (index === -1) {
        tmp.title = undefined
      } else {
        tmp.content.splice(index, 1)
      }

      this.$emit('update:data', tmp)
      let active = this.active
      if (index === 0) {
        if (data.title) {
          active = -1
        } else {
          active = 0
        }
      } else if (index === -1) {
        active = 0
      } else {
        active = index - 1
      }
      this.$emit('update:active', active)
    },
    handleUp(index) {
      const {data} = this
      const tmp = {...data}
      const content = tmp.content
      const upIndex = index - 1
      const currentItem = content[index]
      content[index] = content[upIndex]
      content[upIndex] = currentItem

      this.$emit('update:data', tmp)
      this.$emit('update:active', upIndex)
    },
    handleDown(index) {
      const {data} = this
      const tmp = {...data}
      const content = tmp.content
      const downIndex = index + 1
      const currentItem = content[index]
      content[index] = content[downIndex]
      content[downIndex] = currentItem

      this.$emit('update:data', tmp)
      this.$emit('update:active', downIndex)
    },
    handleAdd(type) {
      const tmp = {...this.data}
      if (type === 'title') {
        tmp.title = {
          id: Date.now(),
          text: '',
          style: '',
          fontSize: 26,
          lineHeight: 42
        }
        this.$emit('update:data', tmp)
      }

      if (type === 'img') {
        this.fileShow = true
        const index = setInterval(() => {
          if (this.$refs.opsFileChange) {
            this.$refs.opsFileChange.click()
            clearInterval(index)
          }
        }, 200)
      }
      if (type === 'text') {
        tmp.content.push({
          id: Date.now(),
          type: 'text',
          text: '',
          style: '',
          fontSize: 17,
          lineHeight: 30
        })
        this.$emit('update:data', tmp)
        this.$emit('update:active', tmp.content.length - 1)
      }
    },
    handleFileChange(event) {
      const file = event.target.files[0]
      if (file) {
        this.fileShow = false
        const that = this
        const fileReader = new FileReader()
        fileReader.readAsDataURL(file)
        fileReader.onload = function (event) {
          const result = event.target.result
          if (result) {
            const tmp = {...that.data}
            tmp.content.push({
              id: Date.now(),
              type: 'img',
              src: result,
              style: ''
            })
            that.$emit('update:data', tmp)
          } else {
            this.$message.error('未选择图片')
          }
        }
      } else {
        this.$message.error('未选择图片')
      }
    },
    doExport() {
      const phoneContext = document.querySelector('div.x-render-phone-main')
      phoneContext.scrollTop = 0
      html2canvas(phoneContext, {
        background: "#ffffff", // 一定要添加背景颜色，否则出来的图片，背景全部都是透明的
        scale: 6, // 处理模糊问题
      }).then((canvas) => {
        this.doGenerateImage(canvas)
      })
    },
    doGenerateImage(canvas) {
      const downloadByBlob = function (blobObj) {
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = window.URL.createObjectURL(blobObj)
        link.download = `${parseTime(new Date())}.jpg`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }

      //第一个参数是回调函数
      canvas.toBlob(
          function (blob) {
            const newImg = document.createElement("img")
            const url = window.URL.createObjectURL(new Blob([blob]))
            downloadByBlob(blob)
            //加载后销毁
            newImg.onload = function () {
              URL.revokeObjectURL(url)
            }
          }, "image/jpeg", 1)

    }
  }
}
</script>

<style scoped lang="css">
.x-render-ops {
  width: 300px;
  display: flex;
  flex-flow: column nowrap;
  border: 1px solid #999;
  border-radius: 6px;
  box-sizing: border-box;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  overflow-x: hidden;
  overflow-y: auto;
  min-height: 500px;
  margin-left: 100px;
}


.x-render-ops-btn {
  margin: 8px 4px;
  display: grid;
  grid-template-columns: repeat(4, 70px);
  grid-column-gap: 4px;
  place-items: center;
}

/deep/ .el-button {
  text-align: center !important;
  padding: 8px !important;
}

.x-render-drag-container {
  width: 100%;
  min-height: 300px;
  padding: 0;
}

.x-render-drag-active {
  color: #f44;
}

/* 表单项 */
.x-render-drag-container .x-render-li-item {
  background: white;
  cursor: move;
  position: relative;
  padding: 8px 4px;
  transition: all .35s;
  overflow: hidden;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}


.x-render-drag-container .x-render-li-item .x-render-li-item-icon {
  display: grid;
  grid-template-columns: repeat(3, 20px);
}

.x-render-drag-container .x-render-li-item i {
  cursor: pointer;
}

.x-render-drag-container .x-render-li-item:hover {
  background-color: #409eff;
  color: #fff;
}

.x-render-drag-container .x-render-li-item::before {
  content: '';
  height: 5px;
  width: 100%;
  background: #409eff;
  position: absolute;
  top: 0;
  right: -110%;
  transition: all .3s;
}

/* 表单项激活时 */
.x-render-drag-container .x-render-li-item-active {
  background-color: #409eff;
  color: #fff
}

.x-render-drag-container .x-render-li-item-active::before {
  right: 0;
}
</style>
